// 2. useDrag
import type { App } from "vue";
import defaultImage from "./../assets/images/default.webp";

interface IuseLazy {
  (el: HTMLImageElement, src: string): void;
  install?: (app: App, name: string) => void;
};

export const useLazy: IuseLazy = (el, src) => {
  const options = {
    root: null, // 观察器的根元素，默认为整个视窗
    rootMargin: "0px", // 根元素边界距离，默认为0
    threshold: 0, // 目标元素可见比例达到该阈值时触发回调函数 0~1.0
  };
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      // entry.isIntersecting === true || entry.intersectionRatio > 0
      if (entry.intersectionRatio > 0) {
        el.src = src;
        observer.unobserve(el);
      } else {
        el.src = defaultImage;
      }
    });
  }, options);
  observer.observe(el);
};

useLazy.install = (app, directiveName = "lazy") => {
  app.directive(directiveName, {
    mounted(el, binding) {
      useLazy(el, binding.value);
    },
  });
  return app
};

// vue 插件接收一个 install 函数
// 用法： app.use(useLazy)
export default useLazy